﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Terraria.GameContent.UI.Elements;
using Terraria.Localization;
using Terraria.UI;

namespace Terraria.ModLoader.UI
{
	// Token: 0x0200027B RID: 635
	internal class UIDownloadMods : UIState
	{
		// Token: 0x06001A04 RID: 6660 RVA: 0x004273C0 File Offset: 0x004255C0
		public override void OnInitialize()
		{
			this.loadProgress = new UILoadProgress();
			this.loadProgress.Width.Set(0f, 0.8f);
			this.loadProgress.MaxWidth.Set(600f, 0f);
			this.loadProgress.Height.Set(150f, 0f);
			this.loadProgress.HAlign = 0.5f;
			this.loadProgress.VAlign = 0.5f;
			this.loadProgress.Top.Set(10f, 0f);
			base.Append(this.loadProgress);
			UITextPanel<string> uitextPanel = new UITextPanel<string>(Language.GetTextValue("UI.Cancel"), 0.75f, true);
			uitextPanel.VAlign = 0.5f;
			uitextPanel.HAlign = 0.5f;
			uitextPanel.Top.Set(170f, 0f);
			uitextPanel.OnMouseOver += UICommon.FadedMouseOver;
			uitextPanel.OnMouseOut += UICommon.FadedMouseOut;
			uitextPanel.OnClick += this.CancelClick;
			base.Append(uitextPanel);
		}

		// Token: 0x06001A05 RID: 6661 RVA: 0x004274EC File Offset: 0x004256EC
		public override void OnActivate()
		{
			this.loadProgress.SetText(Language.GetTextValue("tModLoader.MBDownloadingMod", this.name + ": ???"));
			this.loadProgress.SetProgress(0f);
			if (UIModBrowser.PlatformSupportsTls12)
			{
				ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
			}
			if (this.modsToDownload != null && this.modsToDownload.Count > 0)
			{
				this.client = new WebClient();
				ServicePointManager.ServerCertificateValidationCallback = ((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) => true);
				this.SetCancel(new Action(this.client.CancelAsync));
				this.client.DownloadProgressChanged += this.Client_DownloadProgressChanged;
				this.client.DownloadFileCompleted += this.Client_DownloadFileCompleted;
				this.currentDownload = this.modsToDownload.Dequeue();
				this.loadProgress.SetText(Language.GetTextValue("tModLoader.MBDownloadingMod", string.Format("{0}: {1}", this.name, this.currentDownload.displayname)));
				this.client.DownloadFileAsync(new Uri(this.currentDownload.download), ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
				return;
			}
			Interface.modBrowser.ClearItems();
			Main.menuMode = 10007;
			if (this.missingMods.Count > 0)
			{
				Interface.infoMessage.SetMessage(Language.GetTextValue("tModLoader.MBModsNotFoundOnline", string.Join(",", this.missingMods)));
				Interface.infoMessage.SetGotoMenu(10007, null);
				Main.menuMode = 10013;
			}
		}

		// Token: 0x06001A06 RID: 6662 RVA: 0x004276B0 File Offset: 0x004258B0
		private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
		{
			if (e.Error != null)
			{
				if (e.Cancelled)
				{
					Interface.modBrowser.ClearItems();
					Main.menuMode = 10007;
				}
				else
				{
					HttpStatusCode httpStatusCode = this.GetHttpStatusCode(e.Error);
					if (httpStatusCode == HttpStatusCode.ServiceUnavailable)
					{
						Interface.errorMessage.SetMessage(Language.GetTextValue("tModLoader.MBExceededBandwidth"));
						Interface.errorMessage.SetGotoMenu(0);
						Interface.errorMessage.SetFile(ErrorLogger.LogPath);
						Main.gameMenu = true;
						Main.menuMode = 10005;
					}
					else
					{
						Interface.errorMessage.SetMessage(Language.GetTextValue("tModLoader.MBUnknownMBError"));
						Interface.errorMessage.SetGotoMenu(0);
						Interface.errorMessage.SetFile(ErrorLogger.LogPath);
						Main.gameMenu = true;
						Main.menuMode = 10005;
					}
				}
				File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
				return;
			}
			if (!e.Cancelled)
			{
				File.Copy(ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod", ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + this.currentDownload.mod + ".tmod", true);
				File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
				if (!this.currentDownload.update)
				{
					Interface.modBrowser.aNewModDownloaded = true;
				}
				else
				{
					Interface.modBrowser.aModUpdated = true;
				}
				if (this.modsToDownload.Count != 0)
				{
					this.currentDownload = this.modsToDownload.Dequeue();
					this.loadProgress.SetText(Language.GetTextValue("tModLoader.MBDownloadingMod", string.Format("{0}: {1}", this.name, this.currentDownload.displayname)));
					this.loadProgress.SetProgress(0f);
					this.client.DownloadFileAsync(new Uri(this.currentDownload.download), ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
					return;
				}
				this.client.Dispose();
				this.client = null;
				Interface.modBrowser.ClearItems();
				Main.menuMode = 10007;
				if (this.missingMods.Count > 0)
				{
					Interface.infoMessage.SetMessage(Language.GetTextValue("tModLoader.MBModsNotFoundOnline", string.Join(",", this.missingMods)));
					Interface.infoMessage.SetGotoMenu(10000, null);
					Main.menuMode = 10013;
					return;
				}
			}
			else
			{
				File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
			}
		}

		// Token: 0x06001A07 RID: 6663 RVA: 0x00012744 File Offset: 0x00010944
		private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
		{
			this.SetProgress(e);
		}

		// Token: 0x06001A08 RID: 6664 RVA: 0x0001274D File Offset: 0x0001094D
		internal void SetDownloading(string name)
		{
			this.name = name;
		}

		// Token: 0x06001A09 RID: 6665 RVA: 0x00012756 File Offset: 0x00010956
		public void SetCancel(Action cancelAction)
		{
			this.cancelAction = cancelAction;
		}

		// Token: 0x06001A0A RID: 6666 RVA: 0x0001275F File Offset: 0x0001095F
		internal void SetProgress(DownloadProgressChangedEventArgs e)
		{
			this.SetProgress(e.BytesReceived, e.TotalBytesToReceive);
		}

		// Token: 0x06001A0B RID: 6667 RVA: 0x00012773 File Offset: 0x00010973
		internal void SetProgress(long count, long len)
		{
			UILoadProgress uiloadProgress = this.loadProgress;
			if (uiloadProgress == null)
			{
				return;
			}
			uiloadProgress.SetProgress((float)count / (float)len);
		}

		// Token: 0x06001A0C RID: 6668 RVA: 0x0001278A File Offset: 0x0001098A
		private void CancelClick(UIMouseEvent evt, UIElement listeningElement)
		{
			Main.PlaySound(10, -1, -1, 1, 1f, 0f);
			Action action = this.cancelAction;
			if (action == null)
			{
				return;
			}
			action();
		}

		// Token: 0x06001A0D RID: 6669 RVA: 0x00427968 File Offset: 0x00425B68
		internal void SetModsToDownload(List<string> specialModPackFilter, List<UIModDownloadItem> items)
		{
			this.modsToDownload.Clear();
			this.missingMods.Clear();
			using (List<string>.Enumerator enumerator = specialModPackFilter.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					string desiredMod = enumerator.Current;
					UIModDownloadItem uimodDownloadItem = items.FirstOrDefault((UIModDownloadItem x) => x.mod == desiredMod) ?? null;
					if (uimodDownloadItem == null)
					{
						this.missingMods.Add(desiredMod);
					}
					else if (uimodDownloadItem.installed == null || uimodDownloadItem.update)
					{
						this.modsToDownload.Enqueue(uimodDownloadItem);
					}
				}
			}
		}

		// Token: 0x06001A0E RID: 6670 RVA: 0x00427A1C File Offset: 0x00425C1C
		private HttpStatusCode GetHttpStatusCode(Exception err)
		{
			if (err is WebException)
			{
				WebException ex = (WebException)err;
				if (ex.Response is HttpWebResponse)
				{
					HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response;
					return httpWebResponse.StatusCode;
				}
			}
			return (HttpStatusCode)0;
		}

		// Token: 0x0400175B RID: 5979
		private UILoadProgress loadProgress;

		// Token: 0x0400175C RID: 5980
		private string name;

		// Token: 0x0400175D RID: 5981
		private Action cancelAction;

		// Token: 0x0400175E RID: 5982
		private Queue<UIModDownloadItem> modsToDownload = new Queue<UIModDownloadItem>();

		// Token: 0x0400175F RID: 5983
		private List<string> missingMods = new List<string>();

		// Token: 0x04001760 RID: 5984
		private WebClient client;

		// Token: 0x04001761 RID: 5985
		private UIModDownloadItem currentDownload;
	}
}
